package com.jt.assistant.ui

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Vibrator
import android.text.TextUtils
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.ToastUtils
import com.jt.assistant.R
import com.jt.assistant.adapter.ScanAdapter
import com.jt.assistant.base.GlobalConfig
import com.jt.assistant.bean.ScanCarton
import com.jt.assistant.bean.ScanDataBean
import com.jt.assistant.utils.FastClickUtil
import com.jt.assistant.utils.ScanCartonCodeHelper
import com.jt.assistant.viewmodel.HomeViewModel
import com.orhanobut.logger.Logger
import com.tencent.mmkv.MMKV
import com.yzp.mvvmlibrary.base.BaseActivity
import kotlinx.android.synthetic.main.activity_scan.*
import java.util.regex.Pattern

/**
 * 退仓扫码 14987468
 */
class ReturnScanActivity : BaseActivity<HomeViewModel>() {
    private val mAdapter by lazy {
        ScanAdapter(
            ArrayList<ScanCarton>()
        )
    }
    private var mScanData: ScanDataBean? = null
    private val mUploadList = ArrayList<ScanCarton>()
    private val mScanCartonList = ArrayList<ScanCarton>()
    private val mHandle by lazy { Handler() }
    private var mScannedCarton = 0

    private val mRunnable = Runnable {
        val mUploadList = ArrayList<ScanCarton>()
        mScanCartonList.forEach {
            if (it.hasScan && !it.hasUpload) {
                mUploadList.add(it)
            }
        }
        viewModel.sendReturnsScanLog(mUploadList)
    }


    override fun layoutId(): Int = R.layout.activity_return_scan

    override fun initView(savedInstanceState: Bundle?) {
        set_scan.initCamera(this, GlobalConfig.SCAN_TYPE_OUT)
        with(rv_scan) {
            layoutManager = LinearLayoutManager(context)
            adapter = mAdapter
        }
    }

    @SuppressLint("SetTextI18n")
    override fun initData() {
        mScanData = GsonUtils.fromJson(
            intent.getStringExtra(GlobalConfig.SCAN_DATA).toString(),
            ScanDataBean::class.java
        )
        mScanCartonList.addAll(ScanCartonCodeHelper.createReturnScanList(mScanData!!))
        log(mScanCartonList)

        mScannedCarton = mScanData!!.scannedCarton
        bt_totalCarton.text = "总箱数: ${mScanData!!.totalCarton}"
        bt_ScanCarton.text = "已扫码: ${scanNumber()}"


    }

    override fun initListener() {
        set_scan.setOnScanListener {

            if (it.isNullOrEmpty()) {
                ToastUtils.showShort("请输入箱码")
                set_scan.clearData()
                return@setOnScanListener
            }
            if (!checkCartonCode(it)) {
                set_scan.clearData()
                return@setOnScanListener
            }
            hasScanData()
            set_scan.clearData()
        }

        bt_totalCarton.setOnClickListener {
            MMKV.defaultMMKV()
                .putString(
                    GlobalConfig.SCAN_DATA,
                    intent.getStringExtra(GlobalConfig.SCAN_DATA).toString()
                )
            MMKV.defaultMMKV()
                .putString(GlobalConfig.SCAN_CARTON_LIST, GsonUtils.toJson(mScanCartonList))
            startActivity(Intent(this@ReturnScanActivity, WaybillStateActivity::class.java))
        }

        bt_ScanCarton.setOnClickListener {
            MMKV.defaultMMKV()
                .putString(GlobalConfig.SCAN_CARTON_LIST, GsonUtils.toJson(mScanCartonList))
            startActivity(Intent(this@ReturnScanActivity, CartonStateActivity::class.java))
        }


        tv_upload.setOnClickListener {
            //手动上报
            if (FastClickUtil.isFastClick()) { //防重复点击
                return@setOnClickListener
            }

            val uploadList = ArrayList<ScanCarton>()
            mScanCartonList.forEach {
                if (it.hasScan && !it.hasUpload) {
                    uploadList.add(it)
                }
            }

            if (uploadList.size == 0) {
                speakString("数据已上传")
                return@setOnClickListener
            }
            if (mHandle.hasCallbacks(mRunnable)) {
                mHandle.removeCallbacks(mRunnable)
            }
            viewModel.sendReturnsScanLog(mUploadList)
        }


        //上传的箱码回传
        viewModel.mReturnsScanCarton.observe(this, {
            //将数据置为已上传状态
            it.forEach {
                Logger.e("########${it.cartonCode}")
                for (position in mScanCartonList.indices) {
                    if (it.cartonCode == mScanCartonList[position].cartonCode && !mScanCartonList[position].hasUpload) {
                        mScanCartonList[position].hasUpload = true
                    }
                }
            }
            bt_ScanCarton.text = "已扫码: ${scanNumber()}"
            ToastUtils.showShort("上传成功")
            updateList()
            if (scanNumber().toInt() >= mScanCartonList.size) {//mScanCartonList
                speakString("扫码已完成")
                finish()
            }
        })


        viewModel.mSendReturnsScanLog.observe(this, {
            if (it.isSuccess()) {
                tv_codeListStatus.setTextColor(Color.GRAY)
                tv_codeListStatus.text = "待上传列表"
            } else {
                tv_codeListStatus.text = "上传失败请手动上传"
                tv_codeListStatus.setTextColor(Color.RED)
            }
        })
    }

    private fun updateList() {
        mAdapter.data.clear()
        mScanCartonList.forEach {
            if (it.hasScan && !it.hasUpload) {
                mAdapter.data.add(0, it)
            }
        }
        mAdapter.notifyDataSetChanged()
    }

    private fun scanNumber(): String {
        var num = 0
        mScanCartonList.forEach {
            if (it.hasScan && it.hasUpload) {
                num++
            }
        }
        return num.toString()
    }

    override fun handleEvent(msg: String) {
        speakString("上传失败请检查网络")
        ToastUtils.showShort("网络请求失败,上传失败请检查网络: $msg")
    }

    private fun checkCartonCode(code: String): Boolean {
        if (!isCartonCode(code)) {
            speakString("箱码错误")
            return false
        }

        for (position in mScanCartonList.indices) {
            if (code == mScanCartonList[position].cartonCode) {
                return if (mScanCartonList[position].hasScan) {
                    speakString("重复扫码")
                    false
                } else {
                    //将数据置为已扫码状态
                    mScanCartonList[position].hasScan = true
                    mAdapter.data.add(0, mScanCartonList[position])
                    mAdapter.notifyDataSetChanged()
                    vibrate()
                    true
                }
            }
        }
        Logger.e("########${code}")
        speakString("箱码错误")
        return false
    }


    private fun hasScanData() {
        if (mHandle.hasCallbacks(mRunnable)) {
            mHandle.removeCallbacks(mRunnable)
        }
        mHandle.postDelayed(mRunnable, 3000)
    }

    private fun vibrate() {
        val vibrator: Vibrator = getSystemService(VIBRATOR_SERVICE) as Vibrator
        vibrator.vibrate(200)
    }

    private fun isCartonCode(cartonCode: String): Boolean {
        //check cartonCode
        if (TextUtils.isEmpty(cartonCode)) {
            return false
        }
        val newCarton = "^[a-zA-Z0-9]{15}-\\d+-\\d+-$"
        val numberCarton = "^[0-9]{18}$"
        val patternNew = Pattern.compile(newCarton)
        val patternNum = Pattern.compile(numberCarton)
        return patternNum.matcher(cartonCode).find() || patternNew.matcher(cartonCode).find()
    }
}